﻿using B.S.DataBase.MyProject.Domain.HealthMonitoring;
using B.S.DataBase.MyProject.Domain.Infrastructures;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.HealthMonitoringCommand;

namespace MedicalPCTerminal.Write.API.Appcation.CommandHandlers.HealthMonitoringCommandHandler
{
    /// <summary>
    /// 修改BMI
    /// </summary>
    public class UpdateBMIMonitoringCommandHandler : IRequestHandler<UpdateBMIMonitoringCommand, APIResult<int>>
    {

        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly SqlSugarContext sqlSugar;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="sqlSugar">SqlSugar</param>
        public UpdateBMIMonitoringCommandHandler(SqlSugarContext sqlSugar)
        {
            this.sqlSugar = sqlSugar;
        }
        public async Task<APIResult<int>> Handle(UpdateBMIMonitoringCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var list = sqlSugar.db.Queryable<BMIMonitoring>().Where(x => x.BId == request.BId).First();
                list.Weight = request.Weight;
                list.Higher = request.Higher;
                list.BMI = Math.Round(list.Weight / ((list.Higher / 100) * (list.Higher / 100)), 2);
                var res = sqlSugar.db.Updateable(list).ExecuteCommand();
                if (res > 0)
                {
                    result.Code = APIEnum.修改成功;
                    result.Msg = APIEnum.修改成功.ToString();
                    result.data = res;
                }
                else
                {
                    result.Code = APIEnum.修改失败;
                    result.Msg = APIEnum.修改失败.ToString();
                    result.data = res;
                }

                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
